using System;
using System.Collections.Generic;
using System.Text;
using Forecast.Database;

namespace Forecast.Business
{
    public class UpdatePlayer
    {
        #region Variables

        private IList<Player> _allPlayers;
        private IList<Holding> _allHoldings;
        private IList<Offer> _allOffers;

        #endregion
        #region Interface

        public void Execute(IList<Player> allPlayers, IList<Holding> allHoldings, IList<Offer> allOffers)
        {
            _allPlayers = allPlayers;
            _allHoldings = allHoldings;
            _allOffers = allOffers;

            foreach (Player player in _allPlayers)
            {
                CheckOffers(player);
            }
        }

        #endregion
        #region Helper methods

        private void CheckOffers(Player player)
        {
            foreach (Offer offer in _allOffers)
            {
                if (offer.PlayerId != player.Id)
                    continue;
                if (!offer.IsActive)
                    continue;
                if (offer.IsAccepted)
                    continue;
                if (offer.EndDate >= DateTime.Today)
                    continue;
                RemoveOffer(offer, player);
            }
        }

        private void RemoveOffer(Offer offer, Player player)
        {
            offer.IsActive = false;
            if (offer.IsBuy)  
            {
                player.Cash += (offer.Price * offer.NumPredictions);
            }
            else
            {
                Holding holding = GetHolding(offer.PredictionId, player);
                holding.NumPredictions += offer.NumPredictions;
            }
        }

        private Holding GetHolding(int predictionId, Player player)
        {
            foreach (Holding holding in _allHoldings)
            {
                if (holding.PredictionId != predictionId)
                    continue;
                if (holding.PlayerId == player.Id)
                    return holding;
            }
            Holding newHolding = new Holding();
            newHolding.Id = -1;
            newHolding.NumPredictions = 0;
            newHolding.PlayerId = player.Id;
            newHolding.PredictionId = predictionId;
            _allHoldings.Add(newHolding);
            return newHolding;
        }

        #endregion
        #region Properties

        public IList<Player> UpdatePlayerPlayers
        {
            get { return _allPlayers; }
        }

        public IList<Offer> UpdatePlayerOffers
        {
            get { return _allOffers; }
        }

        public IList<Holding> UpdatePlayerHoldings
        {
            get { return _allHoldings; }
        }

        #endregion
    }
}
